import fs from 'fs'
import resolve from '@rollup/plugin-node-resolve'
import babel from '@rollup/plugin-babel'
import commonjs from '@rollup/plugin-commonjs'
// import typescript from '@rollup/plugin-typescript'
import postcss from 'rollup-plugin-postcss'
import { terser } from 'rollup-plugin-terser'
import dts from 'rollup-plugin-dts'
import { extractMainStrData } from './build/index.js'

const commaStr = process.argv[3]
const isAll = commaStr === '--all'
const componentName = commaStr.slice(2)
const homePath = './src' // 组件主目录
const mainPath = `${homePath}/index.ts` // 入口文件位置
const mainBuildPath = `dist/index.js` // 入口文件打包后的位置

const mainFileStr = fs.readFileSync(mainPath).toString()
const mainStrs = extractMainStrData(mainFileStr)
console.log('mainStrs====>', mainStrs)
const input = {}
let mainBuildStr = ''
mainStrs.forEach(([comName, dirName]) => {
  mainBuildStr += `export { default as ${comName} } from './${dirName}/index.js';`
  input[dirName] = `${homePath}/${dirName}/index.tsx`
})

// 创建目录
fs.mkdirSync('dist', { recursive: true })
// 写入文件
fs.writeFileSync(mainBuildPath, mainBuildStr)

// 打包忽略文件
const external = ['react', 'react-dom', '**/node_modules/**']

export default [
  {
    input: isAll ? input : `src/${componentName}/index.tsx`,
    // input,
    output: {
      format: 'es',
      sourcemap: true,
      exports: 'auto',
      entryFileNames: isAll ? '[name]/index.js' : `${componentName}/index.js`,
      dir: 'dist',
    },
    plugins: [
      postcss({
        inject: true, // 注入style标签
        // extract: !!options.writeMeta,
        modules: true, // 使用css modules
        // namedExport: true, // 类名导出
        // camelCase: true, // 支持驼峰
        // sass: false, // 是否使用sass
        // less:true,
      }),
      resolve(),
      commonjs(),
      babel({
        presets: ['@babel/preset-env'],
        extensions: ['.js', '.jsx', '.ts', '.tsx', '.scss', '.less'],
        exclude: '**/node_modules/**',
      }),
      terser(),
    ],
    external,
  },
  // 生成 .d.ts 类型声明文件
  {
    input: `${homePath}/index.ts`,
    output: [
      {
        dir: './dist',
        format: 'es',
        name: 'bundleName',
      },
    ],
    plugins: [dts()],
  },
]
